<?php

namespace App\Http\Controllers\Api;

use App\Enums\UserType;
use App\Http\Controllers\Controller;
use App\Http\Resources\UserResource;
use App\Models\User;
use App\Models\VipPackage;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Ugly\Base\Traits\ApiResource;
use App\Jobs\RenewVip;

class UserController extends Controller
{
    use ApiResource;

    public function index(): JsonResponse
    {
        $query = User::search([
            'type' => '=',
            'username' => 'like',
        ], ['vipPackage:id,name', 'parent'])
            ->whereIn('type', [UserType::MEMBER])
            ->orderByDesc('id');

        return $this->paginate($query, UserResource::class);
    }

    // 添加会员
    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'username' => 'required|email|unique:users,username',
            'password' => 'required|min:6',
            'vip_id' => 'required'
        ]);
        $params = $request->only(['username', 'password', 'vip_id']);
        // 验证套餐是否存在
        $vipPackage = VipPackage::query()->findOrFail($params['vip_id']);
        // 创建用户信息
        $params['start_at'] = now();
        $params['end_at'] = date('Y-m-d H:i:s', (strtotime(now()) + $vipPackage->duration * 86400)); // 设置有效期，当前时间加上套餐时长天数，格式化为时间
        $params['status'] = 1;
        $params['type'] = UserType::MEMBER;
        $params['password'] = bcrypt($params['password']);
        $res = User::query()->create($params);
        if(!$res) {
            return $this->failed('添加失败');
        }
        // 发送续费通知
        $log['start_at'] = $params['start_at'];
        $log['end_at'] = $params['end_at'];
        $log['user_id'] = $res->id;
        $log['vip_id'] = $params['vip_id'];
        $log['status'] = 1;
        RenewVip::dispatch($log);

        return $this->success();
    }

    // 修改用户、代理
    public function update(Request $request, $id): JsonResponse
    {
        $params = $request->only(['status', 'vip_id']);

        $user = User::query()->whereIn('type', [UserType::MEMBER, UserType::AGENT])->findOrFail($id);
        if(isset($params['vip_id']) && !empty($params['vip_id'])) {
            return $this->updatePackage($params, $user);
        }
        $res = $user->update($params);
        if (!$res) {
            return $this->failed('状态失败');
        }

        return $this->success();
    }

    protected function updatePackage(array $params, User $user)
    {
        if($user->status == 0) {
            return $this->failed('用户已被禁用，请先启用后再进行操作！');
        }

        $vipPackage = VipPackage::query()->findOrFail($params['vip_id']);
        $userEndAt = $user->end_at ?? now();
        $params['start_at'] = $user->start_at ?? now();
        $params['end_at'] = date('Y-m-d H:i:s', (strtotime($userEndAt) + $vipPackage->duration * 86400));
        $res = $user->update($params);
        if (!$res) {
            return $this->failed('修改失败');
        }
        // 发送续费通知
        $log['start_at'] = now();
        $log['end_at'] = $params['end_at'];
        $log['user_id'] = $user->id;
        $log['vip_id'] = $params['vip_id'];
        $log['status'] = 1;
        RenewVip::dispatch($log);

        return $this->success();
    }

    public function agent_tree()
    {
        $list = User::query()
            ->select(['id', 'username as label', 'parent_id'])
            ->where('type', UserType::AGENT)
            ->get()
            ->toArray();
        $list = $this->treeLevel($list, 0); // treeLevel

        return $this->success($list);
    }

    private function treeLevel($array, $pid): array
    {
        $tree = [];
        foreach ($array as $key => $value) {
            if ($value['parent_id'] == $pid) {
                $value['children'] = $this->treeLevel($array, $value['id']);
                if (! $value['children']) {
                    unset($value['children']);
                }
                $tree[] = $value;
            }
        }

        return $tree;
    }

    // 代理邀请记录
    public function invite(): JsonResponse
    {
        $query = User::query()
            ->where('parent_id', auth('api')->user()->id)
            ->orderByDesc('id');

        return $this->paginate($query, UserResource::class);
    }
}
